<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>进度条</title>
  <style>
    html,
    body {
      margin: 0;
      padding: 0;
    }

    div.poa {

      position: fixed;
      left: 0;
      bottom: 50%;
      transform: translateY(50%);
      transition: all 1s;
    }

    div.poa div {
      width: 0;
      font-size: 30px;
      height: 200px;
      line-height: 200px;
      background-color: #af4baf;
      text-align: center;
      font-weight: 700;
      color: white;
      transition: all 1s;
    }

    div.poa h1 {
      margin-left: 200px;
    }
  </style>
</head>

<body>
  <div class="poa">
    <h1 class="top">进度条👇</h1>

    <div id="progress">
      0%
    </div>

    <h1 class="bottom">进度条👆</h1>

  </div>
  <script>
    let arr = ['hhh', 'ddd', 'eee', 'sss', 'ccc',]

    // 设置一个sleep函数，规定默认延迟时间为1000ms，返回一个Promise函数
    // 内部封装一个定时器
    function sleep(delay = 1000) {
      return new Promise(resolve => {
        setInterval(resolve, delay);
        // setInterval(() => {
        //   resolve()
        // }, delay);
      })
    }
    // 1.  使用for循环进行数组遍历，每次递增div的宽度
    async function showProgress() {
      for (let i = 0; i < arr.length; i++) {
        //等待300ms后执行后面的内容
        await sleep(300)
        let progress = document.querySelector('#progress')
        progress.style.width = i / (arr.length - 1) * document.body.offsetWidth + 'px'
        progress.textContent = i / (arr.length - 1) * 100 + '%'

      }

      // 其他方法

      // 1. 可以通过指定遍历次数进行该操作 👇

      /*

        let num = 8
        for (let i = 0; i < num; i++) {
          await sleep(300)
          let progress = document.querySelector('#progress')
          progress.style.width = i / (num - 1) * document.body.offsetWidth + 'px'
          progress.textContent = (i / (num - 1) * 100).toFixed(0) + '%'
        }

      */

      // 2. 通过每次增加宽度后，获取宽度值，进而通过宽度值计算出百分比👇
      // for (let i = 0; i < arr.length; i++) {
      //   await sleep(300)
      //   let progress = document.querySelector('#progress')
      //   progress.style.width = i / (arr.length - 1) * document.body.offsetWidth + 'px'
      //   progress.textContent = (progress.style.width.replace('px','')*1 / progress.parentNode.offsetWidth) * 100 + '%'
      // }
    }
    showProgress()
  </script>
</body>

</html>